#include "HeartBeatHandlerImp.h"

#include <iostream> // for log

#include "HeartBeatServerImp.h"



namespace frame {
namespace imp {

HeartBeatHandlerImp::HeartBeatHandlerImp(HandlerImp * handlerImp)
: handlerImp(handlerImp)
{
}
HeartBeatHandlerImp::~HeartBeatHandlerImp()  {
}

void HeartBeatHandlerImp::connected(ServerChannelImp* serverChannelImp)  {
    HeartBeatServerImp * serverImp = static_cast<HeartBeatServerImp*>(getServerImp());
    if(serverImp != nullptr){
        if(false == serverImp->addChannel(serverChannelImp)){
            std::cout << "ERROR: channel id is exist already" << std::endl;
            return ;
        }
        if(handlerImp != nullptr){
            handlerImp->connected(serverChannelImp);
        }
    }
}

void HeartBeatHandlerImp::disconnected(ServerChannelImp* serverChannelImp, Error error)  {
    std::cout << "HeartBeatHandlerImp disconnected, will remove the Channel" << std::endl;
    HeartBeatServerImp * serverImp = static_cast<HeartBeatServerImp*>(getServerImp());
    if(serverImp != nullptr){
        if(false == serverImp->removeChannel(serverChannelImp->getId())){
            std::cout << "ERROR: channel id is not exist" << std::endl;
            return ;
        }

        if(handlerImp != nullptr){
            handlerImp->disconnected(serverChannelImp, error);
        }
    }
}

void HeartBeatHandlerImp::read(ServerChannelImp * serverChannelImp, const char * buf,  std::size_t size)  {
    HeartBeatServerImp * serverImp = static_cast<HeartBeatServerImp*>(getServerImp());
    if(serverImp != nullptr){
        auto * channelNode = serverImp->getChannel(serverChannelImp->getId());
        if(channelNode == nullptr){
            std::cout << "ERROR: channel id is not exist" << std::endl;
            return ;
        }
        channelNode->updateLastReadTimestamp();
        if(handlerImp != nullptr){
            handlerImp->read(serverChannelImp, buf, size);
        }
    }
}
void HeartBeatHandlerImp::readException(ServerChannelImp * serverChannelImp, int error)  {
    if(handlerImp != nullptr){
        handlerImp->readException(serverChannelImp, error);
    }
}

void HeartBeatHandlerImp::writed(ServerChannelImp * serverChannelImp, std::size_t size)  {
    HeartBeatServerImp * serverImp = static_cast<HeartBeatServerImp*>(getServerImp());
    if(serverImp != nullptr){
        auto * channelNode = serverImp->getChannel(serverChannelImp->getId());
        if(channelNode == nullptr){
            std::cout << "ERROR: channel id is not exist" << std::endl;
            return ;
        }
        channelNode->updateLastWriteTimestamp();
        if(handlerImp != nullptr){
            handlerImp->writed(serverChannelImp, size);
        }
    }
}
void HeartBeatHandlerImp::writeException(ServerChannelImp * serverChannelImp, int error)  {
    if(handlerImp != nullptr){
        handlerImp->writeException(serverChannelImp, error);
    }
}

} //end of namespace  imp
} //end of namespace  frame
